//
//  ProductInfoViewController1.m
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/4/19.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "ProductInfoViewController1.h"
#import "ProductDetailViewController.h"
#import "MJRefresh.h"
#import "ProdcutDetaiModel.h"
#import "ProductPicTableViewCell.h"
#import "ProductInfoTableViewCell.h"
#import "ProductCommentTableViewCell.h"
#import "ProductRightNaviView.h"
#import "LoginViewController.h"
#import "ShopBagViewController.h"
#import "PurchaseNowViewController.h"
#import "CLZRefreshHeader.h"
#import "ShareView.h"
#import "WXApi.h"

@interface ProductInfoViewController1 ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, PurchaseCommodityDelegate>

@property (weak, nonatomic) IBOutlet UIView *purchaseView;
@property (strong, nonatomic) UIScrollView *bgScrollView;
@property (strong, nonatomic) UITableView *subTableView;
@property (strong, nonatomic) UIWebView *webView;
@property (nonatomic, strong) ProductRightNaviView *rightNaviView;
@property (nonatomic, strong) PurchaseNowViewController *purchaseVC;
@property (nonatomic, strong) PurchaseNowViewController *optionalProductVC;
@property (nonatomic, strong) ShareView *shareView;
@property (weak, nonatomic) IBOutlet UIButton *purchaseBtn;
@property (weak, nonatomic) IBOutlet UIButton *addToShopCartBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spaceLineHeightCons;
@property (weak, nonatomic) IBOutlet UIButton *btnUp;

@property (nonatomic, assign) int lastPosition;
@property (nonatomic, copy) NSString *productId;
@property (nonatomic, assign) NSInteger productNumberInCart;
@property (nonatomic, strong) ProdcutDetaiModel *productModel;
@property (nonatomic, strong) UIView *backView;
@end

@implementation ProductInfoViewController1

-(id)initWithProductId:(NSString *)productId {
    if (self = [super init]) {
        self.productId = productId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.purchaseBtn.layer.cornerRadius = 24.f;
    self.addToShopCartBtn.layer.cornerRadius = 24.f;
    [self.purchaseBtn setBackgroundImage:[UIColor createImageWithColor:[UIColor grayColor]] forState:UIControlStateDisabled];
    self.purchaseBtn.clipsToBounds=YES;
    [self.addToShopCartBtn setBackgroundImage:[UIColor createImageWithColor:[UIColor grayColor]] forState:UIControlStateDisabled];
    self.addToShopCartBtn.clipsToBounds=YES;
    self.spaceLineHeightCons.constant = .33f;
    [self.view addSubview:self.bgScrollView];
    [self.bgScrollView addSubview:self.subTableView];
    [self.bgScrollView addSubview:self.webView];
    self.btnUp.alpha = 0.f;
    self.backView.alpha = 0.f;
    [self setSubTableViewRefreshFooter];
    [self setWebViewRefreshHeader];
    
    [self.view bringSubviewToFront:self.purchaseView];
    [self.view bringSubviewToFront:self.btnUp];
    [self setNaviLeftButton];
    [self getProductInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareWXSuccess:) name:@"WXShareSuccess" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    self.rightNaviView.hidden = NO;
    [super viewWillAppear:animated];
    [self getShopCartNumber];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.rightNaviView.hidden = YES;
    [super viewWillDisappear:animated];
}

- (void)getProductInfo {
    [[LKDHud shareHud] showLoadingView];
    [ApiClient getProductDetailInfo:self.productId didFinishLoaded:^(ProdcutDetaiModel *model, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        [self.subTableView.mj_header endRefreshing];
        if ([model.status isEqual:@(1)]) {
            self.productModel = model;
            if ([self.productModel.data.quantity intValue]==0 && self.productModel.data.quantity) {
                self.purchaseBtn.enabled=NO;
                self.addToShopCartBtn.enabled=NO;

            }
            [self.subTableView reloadData];
            [self.rightNaviView updateFavoriteInfo:self.productModel.data.in_wishlist];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        [self.subTableView.mj_header endRefreshing];
    }];
}

- (void)getShopCartNumber {
    [ApiClient getProductNumberInCart:^(CartCountModel *model, NSString *path) {
        if ([model.status isEqual:@(1)]) {
            self.productNumberInCart = model.data.cart_total.integerValue;
            [self.rightNaviView updateShopCartNumber:model.data.cart_total.integerValue];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

- (UIView *)backView {
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [_backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeShareViewAction:)]];
        _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f];
        [self.navigationController.view addSubview:_backView];
    }
    return _backView;
}

#pragma mark -rightNavi

- (ProductRightNaviView *)rightNaviView {
    if (!_rightNaviView) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _rightNaviView = [[ProductRightNaviView alloc] initWithFrame:CGRectMake(44, 0, width - 44.f, 44.f)];
        __weak typeof(self) weakSelf = self;
        __weak typeof(_rightNaviView) weakNavi = _rightNaviView;
        _rightNaviView.addAttentionBlock = ^() {
            if (!APP_CONTEXT.account) {
                [LoginViewController presentLoginViewController:weakSelf withCompleteBlock:nil];
                return ;
            }
            if (!weakSelf.productModel.data.in_wishlist) {
                [ApiClient addProductToWishList:weakSelf.productId didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        weakSelf.productModel.data.in_wishlist = YES;
                        [weakSelf showHudWithText:@"关注成功"];
                        [weakNavi updateFavoriteInfo:YES];
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    
                }];
            } else {
                [ApiClient deleteProductFromWishList:weakSelf.productId didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        weakSelf.productModel.data.in_wishlist = NO;
                        [weakSelf showHudWithText:@"取消关注成功"];
                        [weakNavi updateFavoriteInfo:NO];
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    
                }];
            }
        };
        _rightNaviView.shareBlock = ^(){
            weakSelf.backView.alpha = 1.f;
            [UIView animateWithDuration:.3f animations:^{
                weakSelf.shareView.top = SCREEN_HEIGHT - self.shareView.height;
            }];
//            weakSelf.shareView.hidden = NO;
        };
        _rightNaviView.addToShopBagBlock = ^() {
            ShopBagViewController *shopBagVC = [[ShopBagViewController alloc] init];
            shopBagVC.enableBack = YES;
            [weakSelf.navigationController pushViewController:shopBagVC animated:YES];
        };
        [self.navigationController.navigationBar addSubview:_rightNaviView];
    }
    return _rightNaviView;
}

- (void)showHudWithText:(NSString *)str {
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.contentColor = [UIColor blackColor];
    [self.view addSubview:HUD];
    HUD.labelText = str;
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_select_selectd"]] ;
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];
}

#pragma mark -shareView
- (ShareView *)shareView {
    if (!_shareView) {
        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 199.f)];
        __weak typeof(_shareView) weakShareView = _shareView;
        __weak typeof (self) weakSelf = self;
        _shareView.closeShareViewBlock = ^(){
            weakSelf.backView.alpha = 0.f;
            [UIView animateWithDuration:.3f animations:^{
                weakShareView.top = SCREEN_HEIGHT;
            }];
        };
        [self.navigationController.view addSubview:_shareView];
    }
    _shareView.productModel = self.productModel;
    return _shareView;
}

- (void)closeShareViewAction:(UITapGestureRecognizer *)gesture {
    self.backView.alpha = 0.f;
    [UIView animateWithDuration:.3f animations:^{
        self.shareView.top = SCREEN_HEIGHT;
    }];
}

- (void)shareWXSuccess:(NSNotification *)notify {
    self.backView.alpha = 0.f;
    self.shareView.hidden = YES;
    SendMessageToWXResp *response = notify.object;
    if (response.errCode == 0) {
        [self showHudWithText:@"分享成功"];
    } else {
        [[LKDHud shareHud] showtip:response.errStr];
    }
}

#pragma mark - Property
- (UIScrollView *)bgScrollView
{
    
    if (!_bgScrollView) {
        _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        /*
         底层ScrollView必须scrollEnabled = NO
         */
        _bgScrollView.scrollEnabled = NO;
        _bgScrollView.backgroundColor = [UIColor lightTextColor];
        _bgScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT*2);
        _bgScrollView.delegate = self;
    }
    return _bgScrollView;
}
- (UITableView *)subTableView
{
    if (!_subTableView) {
        _subTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-self.purchaseView.height) style:UITableViewStylePlain];
        _subTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _subTableView.delegate = self;
        _subTableView.dataSource = self;
        __weak typeof(self) weakSelf = self;
        CLZRefreshHeader *header = [CLZRefreshHeader headerWithRefreshingBlock:^{
            [weakSelf getProductInfo];
        }];
        _subTableView.mj_header = header;
    }
    return _subTableView;
}
- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-self.purchaseView.height, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        NSString *url = [NSString stringWithFormat:@"%@/products/%@%@",DOMAIN_ADDRESS,self.productId, @"/description"];
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.scrollView.delegate = self;
    }
    return _webView;
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    switch (indexPath.row) {
        case 0:{
            static NSString *cellID = @"productPicCellIdentifier";
            ProductPicTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!tcell) {
                tcell = [[[NSBundle mainBundle] loadNibNamed:@"ProductPicTableViewCell" owner:self options:nil] lastObject];
            }
            [tcell updateWithProductModel:self.productModel];
            cell = tcell;
        }
            break;
        case 1: {
            static NSString *cellID = @"productInfoCellIdentifier";
            ProductInfoTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!tcell) {
                tcell = [[[NSBundle mainBundle] loadNibNamed:@"ProductInfoTableViewCell" owner:self options:nil] lastObject];
            }
            [tcell updateWithProductModel:self.productModel];
            cell = tcell;

        }
            break;
        case 2: {
            static NSString *cellID = @"productCommentCellIdentifier";
            ProductCommentTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!tcell) {
                tcell = [[[NSBundle mainBundle] loadNibNamed:@"ProductCommentTableViewCell" owner:self options:nil] lastObject];;
            }
            tcell.productId = self.productId;
            if(self.productModel.data.reviews.count > 0) {
                CommentModel *comment = self.productModel.data.reviews[0];
                [tcell updateWithComment:comment];
            } else {
                [tcell updateWithComment:nil];
            }
            cell = tcell;

        }
            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 40.f;
    switch (indexPath.row) {
        case 0:
            height = 419.f;
            break;
        case 1:{
            ProductInfoTableViewCell *cell = (ProductInfoTableViewCell *)[self tableView:self.subTableView cellForRowAtIndexPath:indexPath];
//            height =  [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 1;
            CGSize size=[self.productModel.data.name sizeWithFont:[UIFont systemFontOfSize:16] maxSize:CGSizeMake(SCREEN_WIDTH-14-12, MAXFLOAT)];
            return size.height+1+85-12-20;
        }
            break;
        case 2:
            height = 100.f;
            break;
        default:
            break;
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CGFloat height = 40.f;
    switch (indexPath.row) {
        case 0:
            height = 419.f;
            break;
        case 1:{
            height = 80.f;
        }
            break;
        case 2:
            height = 100.f;
            break;
        default:
            break;
    }
    return height;
}

#pragma mark - SetUp
- (void)setSubTableViewRefreshFooter
{
    __weak typeof(self) weakSelf = self;
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf.bgScrollView scrollRectToVisible:CGRectMake(0, self.webView.originY, SCREEN_WIDTH, SCREEN_HEIGHT) animated:YES];
        [weakSelf.subTableView.mj_footer endRefreshing];
    }];
    
    refreshFooter.arrowView.image = nil;
    
    [refreshFooter setTitle:@"上拉查看图文详情" forState:MJRefreshStateIdle];
    [refreshFooter setTitle:@"上拉查看图文详情" forState:MJRefreshStatePulling];
    [refreshFooter setTitle:@"上拉查看图文详情" forState:MJRefreshStateRefreshing];
    [refreshFooter setTitle:@"上拉查看图文详情" forState:MJRefreshStateWillRefresh];
    [refreshFooter setTitle:@"上拉查看图文详情" forState:MJRefreshStateNoMoreData];
    // 隐藏状态
    //    refreshFooter.stateLabel.hidden = YES;
    self.subTableView.mj_footer = refreshFooter;
    
}
- (void)setWebViewRefreshHeader
{
    __weak typeof(self) weakSelf = self;
    
    MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.bgScrollView scrollRectToVisible:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) animated:YES];
        [weakSelf.webView.scrollView.mj_header endRefreshing];
        self.btnUp.alpha = 0.f;
    }];
    refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    [refreshHeader setTitle:@"下拉回到项目详情" forState:MJRefreshStateIdle];
    [refreshHeader setTitle:@"释放回到项目详情" forState:MJRefreshStatePulling];
    [refreshHeader setTitle:@"释放回到项目详情" forState:MJRefreshStateRefreshing];
    [refreshHeader setTitle:@"释放回到项目详情" forState:MJRefreshStateWillRefresh];
    [refreshHeader setTitle:@"下拉回到项目详情" forState:MJRefreshStateNoMoreData];
    
    self.webView.scrollView.mj_header = refreshHeader;
}

#pragma mark scrollview Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int currentPostion = scrollView.contentOffset.y;
    if ((currentPostion - self.lastPosition > 25) && currentPostion > 0) {
        self.lastPosition = currentPostion;
        [UIView animateWithDuration:.5f animations:^{
            self.purchaseView.top = self.view.height;
        }];
    }else if ((self.lastPosition - currentPostion > 25)) {
        self.lastPosition = currentPostion;
        [UIView animateWithDuration:.5f animations:^{
            self.purchaseView.top = self.view.height - self.purchaseView.height;
        }];
    }
    if (scrollView == self.webView.scrollView) {
        CGPoint offset = scrollView.contentOffset;
        CGRect bounds = scrollView.bounds;
        CGSize size = scrollView.contentSize;
        UIEdgeInsets inset = scrollView.contentInset;
        CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
        CGFloat maximumOffset = size.height;
        if (currentOffset > maximumOffset - SCREEN_HEIGHT) {
            self.btnUp.alpha = 1.f;
        }
    }
}

- (IBAction)topAction:(id)sender {
    self.bgScrollView.contentOffset = CGPointMake(0, 0);
    self.webView.scrollView.contentOffset = CGPointMake(0, 0);
    self.btnUp.alpha = 0.f;
}

- (PurchaseNowViewController *)purchaseVC {
    if (!_purchaseVC) {
        if (self.productModel.data.options.count > 0) {
        }
        _purchaseVC = [[PurchaseNowViewController alloc] initWithProductModel:self.productModel];
        _purchaseVC.view.backgroundColor = [UIColor clearColor];
        _purchaseVC.delegate = self;
    }
    return _purchaseVC;
}

- (PurchaseNowViewController *)optionalProductVC {
    if (!_optionalProductVC) {
        _optionalProductVC = [[PurchaseNowViewController alloc] initWithProductModel:self.productModel isOptionalProductToCart:YES];
        _optionalProductVC.view.backgroundColor = [UIColor clearColor];
        _optionalProductVC.delegate = self;
    }
    return _optionalProductVC;
}

- (IBAction)purchaseNowAction:(id)sender {
    if(!APP_CONTEXT.account) {
        [LoginViewController presentLoginViewController:self withCompleteBlock:nil];
        return;
    }
    self.backView.alpha = 1.f;
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.purchaseVC];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        navi.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }else{
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    [controller presentViewController:navi animated:YES completion:^{
    }];
}

- (void)closePurchaseViewController:(PurchaseNowViewController *)purchaseVC {
    if (purchaseVC == self.purchaseVC) {
        self.backView.alpha = 0.f;
        [self.purchaseVC dismissViewControllerAnimated:YES completion:^{
            self.purchaseVC = nil;
        }];
    } else {
        self.backView.alpha = 0.f;
        [self.optionalProductVC dismissViewControllerAnimated:YES completion:^{
            self.optionalProductVC = nil;
        }];
    }
}

- (void)addOptionalProductToShopBag:(PurchaseNowViewController *)purchaseVC success:(BOOL)success {
    self.backView.alpha = 0.f;
    [self.optionalProductVC dismissViewControllerAnimated:YES completion:^{
        self.optionalProductVC = nil;
    }];
    if (success) {
        [self showHudWithText:@"添加成功"];
        [self.rightNaviView updateShopCartNumber:++self.productNumberInCart];
        [self getShopCartNumber];
    }
}

- (IBAction)addToShopCartAction:(id)sender {
    if (self.productModel.data.options.count > 0) {
        self.backView.alpha = 1.f;
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.optionalProductVC];
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            navi.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }else{
            self.modalPresentationStyle=UIModalPresentationCurrentContext;
        }
        UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
        [controller presentViewController:navi animated:YES completion:^{
            
        }];
    } else {
        [[LKDHud shareHud] showLoadingView];
        [ApiClient addProductToShopBag:self.productId quantity:1 options:nil didFinishLoaded:^(KXJson *json, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
            if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                [self showHudWithText:@"添加成功"];
                [self.rightNaviView updateShopCartNumber:++self.productNumberInCart];
                [self getShopCartNumber];
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
        }];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
